package com.zlq.cn.service.un;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zlq.cn.api.ResponseException;
import com.zlq.cn.bootstrap.SignApiBootstrap;
import com.zlq.cn.config.Config;
import com.zlq.cn.config.FinderConfiguration;
import com.zlq.cn.config.OkhttpConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class IosService {
    @Resource
    private FinderConfiguration finderConfiguration;

    public boolean buyAppVerify(String transactionId, String receipt, String project) {
        JSONObject params = new JSONObject();
        Integer version = Integer.parseInt(SignApiBootstrap.get().getVersion().substring(0, 1));
        String password;
        if (Config.PROJECT_FANYI.equals(project)) {
            password = finderConfiguration.getFanyiIosPayPasswordPro();
        } else if (Config.PROJECT_DZMY.equals(project)) {
            password = finderConfiguration.getFanyiIosPayPasswordPro();
        } else if (Config.PROJECT_AI.contains(project)) {
            password = finderConfiguration.getAiIosPayPasswordPro();
        } else if (version >= 1) {
            password = finderConfiguration.getIosPayPasswordPro();
        } else {
            password = finderConfiguration.getIosPayPasswordDev();
        }
        params.put("password", password);
        params.put("receipt-data", receipt);
        Request request = new Request.Builder()
                .url(Config.IOS_VERIFY_RECEIPT)
                .post(RequestBody.create(params.toJSONString(), MediaType.parse("application/json;charset=utf-8")))
                .build();
        try {
            JSONObject jsonObject = JSON.parseObject(OkhttpConfig.okHttpClient.newCall(request).execute().body().string());
            // 该订单是沙盒订单，重新用沙盒查询
            if (21007 == jsonObject.getIntValue("status")) {
                request = new Request.Builder()
                        .url(Config.IOS_SAND_BOX_VERIFY_RECEIPT)
                        .post(RequestBody.create(params.toJSONString(), MediaType.parse("application/json;charset=utf-8")))
                        .build();
                jsonObject = JSON.parseObject(OkhttpConfig.okHttpClient.newCall(request).execute().body().string());
            }
            if (0 != jsonObject.getIntValue("status")) {
                ResponseException.resultApiError("支付失败");
            }
            List<JSONObject> jsonArray = JSON.parseArray(jsonObject.getJSONObject("receipt").getString("in_app"), JSONObject.class);
            List<String> transactionIds = jsonArray.stream().map(jsonObject1 -> jsonObject1.getString("transaction_id")).collect(Collectors.toList());
            return transactionIds.contains(transactionId);
        } catch (Exception e) {
            log.error("苹果查询订单失败", e);
            ResponseException.resultApiError("苹果查询订单失败");
        }
        return false;
    }
}
